<template>
  <!-- <v-scale-screen fullScreen> -->
  <div class="dashboard-container">
    <!-- 头部导航栏 -->
    <div class="header">
      <div class="nav-left">
        <!-- <div class="home-icon">⌂</div> -->
        <div class="nav-dropdown">
          <el-select
            v-model="workShop"
            style="width: 120px"
            clearable
            placeholder="请选择车间"
            @change="changeWorkShop"
          >
            <el-option
              v-for="item in workShopOpts"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <div class="filter-dropdown">
            <el-select
              v-model="lines"
              style="width: 150px"
              clearable
              multiple
              collapse-tags
              placeholder="请选择产线"
              @change="changeLines"
            >
              <el-option
                v-for="item in productionLineOpts"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <div class="filter-dropdown">
            <el-date-picker
              v-model="selectTime"
              type="date"
              placeholder="选择日期"
              style="width: 150px"
              value-format="yyyy-MM-dd"
              @change="changeTime"
            >
            </el-date-picker>
          </div>
        </div>
      </div>
      <div class="title">产线智能可视化大屏</div>
      <div class="nav-right">
        <div class="flBtn" @click="fluch">刷新</div>
        <span class="date">{{ currentDate }}</span>
        <span class="time">{{ currentTime }}</span>
        <div v-if="!showType">
          <img
            style="width: 24px; height: 24px; cursor: pointer"
            @click="fullScreen"
            src="../images/sf.png"
            alt=""
          />
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content">
      <!-- 左侧内容栏 -->
      <div class="left-content">
        <!-- 关键工序不良率 -->
        <div class="panel">
          <div class="hander">
            <div class="panel-header">
              <div class="panel-title">关键工序不良率</div>
            </div>
            <el-select
              v-model="selProcess"
              style="margin-left: 20px"
              placeholder="请选择工序"
              @change="changeSelProcess"
            >
              <el-option
                v-for="item in processList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
          <div
            class="panel-chart"
            :style="{ height: showType ? '420px' : '300px' }"
            id="defect-rate-chart"
          ></div>
        </div>

        <!-- FQC 批合格率 -->
        <div class="panel">
          <div class="hander">
            <div class="panel-header">
              <div class="panel-title">FQC批合格率</div>
            </div>
          </div>
          <div
            class="panel-chart"
            :style="{ height: showType ? '420px' : '300px' }"
            id="fqc-chart"
          ></div>
        </div>
      </div>

      <!-- 右侧内容栏 -->
      <div class="right-content">
        <!-- 实时产能趋势图 -->
        <div class="panel">
          <div class="hander">
            <div class="panel-header">
              <div class="panel-title">实时产能趋势图</div>
            </div>
          </div>
          <div
            class="panel-chart"
            :style="{ height: showType ? '420px' : '300px' }"
            id="capacity-chart"
          ></div>
        </div>

        <!-- 生产进度 -->
        <div class="panel production-progress">
          <div class="panel-header">
            <div class="panel-title">生产进度</div>
          </div>
          <div
            class="progress-table"
            :style="{ height: showType ? '420px' : '300px' }"
          >
            <table>
              <thead>
                <tr>
                  <th>序号</th>
                  <th>工单</th>
                  <th>产线</th>
                  <th>品号</th>
                  <th>状态</th>
                  <th>计划数量</th>
                  <th>生产数量</th>
                  <th>合格率</th>
                  <th>完成率</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in productionData" :key="index">
                  <td>{{ index + 1 }}</td>
                  <td>{{ item.docNo }}</td>
                  <td>{{ item.lineName }}</td>
                  <td>{{ item.itemCode }}</td>
                  <td :class="`status-${item.moStatus}`">
                    {{ getStatusText(item.moStatus) }}
                  </td>
                  <td>{{ item.planQty }}</td>
                  <td>{{ item.completedQty }}</td>
                  <td>{{ item.passRate ? item.passRate + "%" : "--" }}</td>
                  <td>
                    {{ item.progress ? item.progress + "%" : "--" }}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- </v-scale-screen> -->
</template>

<script>
// 引入 ECharts
import * as echarts from "echarts";
import { workshop, lineList } from "@/api/common.js";
import {
  workOrderProductionProgressTable,
  realTimeCapacityTrend,
  lineFqcBatchPassRate,
  defectRateProcesses,
} from "@/api/workshopLargeScreen.js";

import { getPfocProcessLargeList } from "@/api/common.js";

// import VScaleScreen from "v-scale-screen";

export default {
  name: "ProductionDashboard",
  data() {
    return {
      currentDate: "",
      currentTime: "",
      productionData: [],
      productionLine: "",
      productionLineOpts: [],
      workShop: "",
      workShopOpts: [],

      colorList: [
        "#4dabf7",
        "#38d9a9",
        "#ffe066",
        "#D9001B",
        // "#F2F2F2",
        "#00FFFF",
        "#95F20",
        "#FFFF00",
        "F59A23",
        "D9001B",
        "8400FF",
      ],
      lines: [],
      selectTime: new Date().toISOString().split("T")[0],

      processList: [],
      selProcess: "",
    };
  },

  mounted() {
    this.getWorkshop();
    this.initTime();
    this.fetchProductionData();
    this.getPfocProcessLists();
  },
  props: ["showType"],
  methods: {
    async getPfocProcessLists() {
      const res = await getPfocProcessLargeList();
      this.processList = res.data.data.map((item) => {
        return {
          value: item.id,
          label: item.processName,
        };
      });

      this.selProcess = this.processList[0].value;
    },
    changeSelProcess(val) {
      this.selProcess = val;
      this.fetchDefectRateData();
    },

    fluch() {
      this.fetchProductionData(); //表格
      this.fetchDefectRateData(); //关键工序不良率
      this.fetchFQCData(); //FQC批合格率
      this.fetchCapacityData(); //实时产能趋势图
    },

    changeTime(val) {
      this.selectTime = val;
      this.fetchProductionData(); //表格
      this.fetchDefectRateData(); //关键工序不良率
      this.fetchFQCData(); //FQC批合格率
      this.fetchCapacityData(); //实时产能趋势图
    },
    changeLines(val) {
      this.lines = val;
      this.fetchProductionData(); //表格
      this.fetchDefectRateData(); //关键工序不良率
      this.fetchFQCData(); //FQC批合格率
      this.fetchCapacityData(); //实时产能趋势图
    },
    fullScreen() {
      window.open("/#/O3-line");
    },
    changeWorkShop(val) {
      this.workShop = val;
      this.getlineList();
    },
    async getWorkshop() {
      const res = await workshop();
      console.log("workshop", res.data.data.records);
      if (res) {
        this.workShopOpts = res.data.data.records.map((item) => {
          return {
            value: item.id,
            label: item.workshopName,
          };
        });
        this.workShop = this.workShopOpts[0].value;
        this.getlineList();
      }
    },
    initTime() {
      // 初始化时间
      const now = new Date();
      this.currentDate = this.formatDate(now);
      this.currentTime = this.formatTime(now);

      // 每秒更新时间
      setInterval(() => {
        this.currentTime = this.formatTime(new Date());
      }, 1000);
    },
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    formatTime(date) {
      const hours = date.getHours().toString().padStart(2, "0");
      const minutes = date.getMinutes().toString().padStart(2, "0");
      const seconds = date.getSeconds().toString().padStart(2, "0");
      return `${hours}:${minutes}:${seconds}`;
    },

    getStatusText(status) {
      const statusMap = {
        normal: "正常",
        warning: "警告",
        error: "异常",
      };
      return statusMap[status] || status;
    },

    async getlineList() {
      let data = {
        workshopId: this.workShop,
        current: 1,
        size: 999,
      };

      const res = await lineList(data);

      if (!res) {
        return;
      }
      this.productionLineOpts = res.data.data.records.map((item) => {
        return {
          value: item.id,
          label: item.realityLineName,
        };
      });

      this.lines = [this.productionLineOpts[0].value];

      this.fetchProductionData(); //表格
      this.fetchDefectRateData(); //关键工序不良率
      this.fetchFQCData(); //FQC批合格率
      this.fetchCapacityData(); //实时产能趋势图
    },

    fetchProductionData() {
      // 模拟接口调用，实际项目中替换为真实 API
      console.log("获取生产进度数据接口已调用");

      let data = {
        workshop: this.workShop,
        lines: this.lines,
      };
      workOrderProductionProgressTable(data)
        .then((response) => {
          this.productionData = response.data.data;
        })
        .catch((error) => {
          console.error("获取生产进度数据失败:", error);
        });
    },
    // 预留接口：获取不良率数据
    async fetchDefectRateData() {
      console.log("获取不良率数据接口已调用");

      console.log(111, this.selProcess);

      let data = {
        lines: [this.lines[0]],
        startDate: this.selectTime,
        process: this.selProcess,
      };

      const res = await defectRateProcesses(data);

      const defectRateChart = echarts.init(
        document.getElementById("defect-rate-chart")
      );
      defectRateChart.setOption({
        grid: {
          left: "3%",
          right: "4%",
          bottom: "10%",
          top: "10%",
          containLabel: true,
        },
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: ["p", "UCL", "CL", "LCL"],
          textStyle: {
            color: "#333",
          },
          bottom: 0,
        },
        xAxis: {
          type: "category",
          data: res.data.data.xAxis,
        },
        yAxis: [
          {
            type: "value",
            name: "不良率",
            position: "right",
            axisLabel: {
              color: "#000",
              formatter: "{value} %",
            },
          },
        ],
        series: [
          {
            name: "p",
            type: "line",
            yAxisIndex: 0,
            data: res.data.data.linList3,
            symbol: "circle",
            lineStyle: {
              width: 1,
              color: "#b22021",
            },
            itemStyle: {
              color: "#b22021",
            },
          },
          {
            name: "UCL",
            type: "line",
            yAxisIndex: 0,
            data: res.data.data.linList2,
            symbol: "circle",
            lineStyle: {
              width: 1,
              color: "#698ab3",
            },
            itemStyle: {
              color: "#698ab3",
            },
          },
          {
            name: "CL",
            type: "line",
            yAxisIndex: 0,
            data: res.data.data.linList1,
            symbol: "circle",

            lineStyle: {
              width: 1,
              color: "#bc773c",
            },
            itemStyle: {
              color: "#bc773c",
            },
          },
          {
            name: "LCL",
            type: "line",
            yAxisIndex: 0,
            data: res.data.data.linList4,
            symbol: "circle",
            lineStyle: {
              width: 1,
              color: "#445e79",
            },
            itemStyle: {
              color: "#445e79",
            },
          },
        ],
      });
    },
    // 预留接口：获取 FQC 数据
    async fetchFQCData() {
      console.log("获取 FQC 数据接口已调用");
      let data = {
        workshops: [this.workShop],
        lines: this.lines,
        startDate: this.selectTime,
      };

      const res = await lineFqcBatchPassRate(data);

      let series = this.lines.map((item, index) => {
        return [
          {
            name: this.productionLineOpts.find((its) => its.value == item)
              .label,
            type: "line",
            yAxisIndex: 0,
            data: res.data.data[item + "_line"].map((item) =>
              item ? item * 100 : null
            ),
            symbol: "circle",
            symbolSize: 8,
            lineStyle: {
              width: 2,
              color: this.colorList[index],
            },
            itemStyle: {
              color: this.colorList[index],
            },
          },
        ];
      });

      // 初始化 FQC 图表
      const fqcChart = echarts.init(document.getElementById("fqc-chart"));

      fqcChart.setOption(
        {
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            top: "10%",
            containLabel: true,
          },
          tooltip: {
            trigger: "axis",
            formatter: function (params) {
              let tooltipContent = "";
              var xAxisValue = params[0].name;
              tooltipContent =
                "<div style='margin-bottom:6px'>" + xAxisValue + "</div>";
              params.forEach(function (item) {
                var colorDot =
                  '<span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:' +
                  item.color +
                  ';"></span>';
                tooltipContent +=
                  colorDot +
                  item.seriesName +
                  ":" +
                  `  <div style="display:inline-block;margin:0 5px;font-weight:600">${
                    item.value ? item.value : 0
                  }</div>` +
                  "%<br/>";
              });
              return tooltipContent;
            },
          },
          xAxis: {
            type: "category",
            data: res.data.data.xAxis,
          },
          yAxis: [
            {
              type: "value",
              name: "合格率",
              position: "right",
              axisLabel: {
                color: "#000",
                formatter: "{value} %",
              },
              max: 100,
              min: 0,
              splitLine: {
                show: true,
                lineStyle: {
                  type: "dashed", //y轴分割线类型
                  color: "#ccc",
                  width: 1,
                },
              },
            },
          ],
          series: series.flat(Infinity),
        },
        true
      );
    },
    // 预留接口：获取产能数据
    async fetchCapacityData() {
      let data = {
        workshop: this.workShop,
        lines: this.lines,
        startDate: this.selectTime,
      };

      const res = await realTimeCapacityTrend(data);

      let series = this.lines.map((item, index) => {
        let list = res.data.data.longListHashMap[item];

        let l1 = list.map((it) => {
          return it ? it["upph"] : 0;
        });

        return {
          name: this.productionLineOpts.find((its) => its.value == item).label,
          type: "line",
          yAxisIndex: 0,
          data: l1,
          symbol: "circle",
          symbolSize: 8,
          lineStyle: {
            width: 2,
            color: this.colorList[index],
          },
          itemStyle: {
            color: this.colorList[index],
          },
        };
      });

      // 初始化产能趋势图
      let capacityChart = echarts.init(
        document.getElementById("capacity-chart")
      );
      capacityChart.setOption(
        {
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            top: "10%",
            containLabel: true,
          },
          tooltip: {
            trigger: "axis",
          },
          xAxis: {
            type: "category",
            data: res.data.data.timers,
          },
          yAxis: [
            {
              type: "value",
              name: "产能",
              position: "right",
              // max:3000,
              // min:0,
              splitLine: {
                show: true,
                lineStyle: {
                  type: "dashed", //y轴分割线类型
                  color: "#ccc",
                  width: 1,
                },
              },
            },
          ],
          series: series,
        },
        true
      );
    },
  },
};
</script>

<style scoped>
.dashboard-container {
  height: 100%;
  font-family: "Arial", sans-serif;
  background-color: #ebf8fe;
  color: #fff;
  padding: 0 10px;
  box-sizing: border-box;
}

.header {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 10px;
  background: #fff;
  margin-bottom: 10px;
}

.nav-left {
  display: flex;
  align-items: center;
}

.flBtn {
  border: 1px solid #1e88e5;
  color: #1e88e5;
  padding: 4px 20px;
  margin-left: 20px;
  border-radius: 5px;
  cursor: pointer;
}

.home-icon {
  margin-right: 15px;
  font-size: 20px;
}

.nav-dropdown {
  display: flex;
  align-items: center;
  position: relative;
  margin-right: 10px;
  cursor: pointer;
}

.dropdown-icon {
  margin-left: 5px;
  font-size: 12px;
}

.title {
  left: 50%;
  transform: translateX(-50%);
  position: absolute;
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.nav-right {
  display: flex;
  /* flex-direction: column; */
  align-items: center;
}

.date,
.time {
  font-size: 16px;
  margin: 3px 10px;
  font-weight: 600;
  color: #333;
}

.content {
  display: flex;
   height: 92%;
  /* height: calc(100vh - 60px); */
  gap: 10px;
}

.left-content,
.right-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.panel {
  background: #fff;
  border: 1px solid #63b1d3;
  border-radius: 5px;
  padding: 10px;
  /* height: 420px; */
  /* overflow: auto; */
}
.hander {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.panel-title {
  font-size: 14px;
  font-weight: bold;
  color: #555555;
}

.view-report {
  background-color: transparent;
  border: 1px solid #1e88e5;
  color: #1e88e5;
  padding: 3px 8px;
  border-radius: 3px;
  cursor: pointer;
  font-size: 12px;
  margin-left: 20px;
}

.panel-filters {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

.filter-dropdown {
  margin-left: 10px;
  padding: 5px 10px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
  color: #fff;
  cursor: pointer;
}

.filter-icon {
  margin-left: 5px;
  font-size: 12px;
}

.panel-chart {
  height: 420px;
  width: 100%;
}

.progress-table {
  width: 100%;
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  padding: 8px 10px;
  text-align: center;
  border: 1px solid #79c9e5;
  color: #333;
  font-size: 12px;
}

th {
  background-color: #79c9e5;
  color: #333;
}

.status-normal {
  color: #4caf50;
}

.status-warning {
  color: #ff9800;
}

.status-error {
  color: #f44336;
}
</style>
